package sale.wxb.loveshopping.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import sale.wxb.loveshopping.constant.RedisConst;
import sale.wxb.loveshopping.entity.common.ResultException;
import sale.wxb.loveshopping.entity.model.SysUser;
import sale.wxb.loveshopping.entity.yml.YmlConfigAuthLogin;
import sale.wxb.loveshopping.service.ISysUserService;
import sale.wxb.loveshopping.utils.RedisUtil;

@Component
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private YmlConfigAuthLogin ymlConfigAuthLogin;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.getUserByAccount(username);

        if (sysUser == null) {
            throw new ResultException("该账号不存在, 请检查是否输入有误");
        }

        boolean isNotLocked = true;
        // 判断账号是否锁定
        if (!ObjectUtils.isEmpty(sysUser)) {
            String key = redisUtil.getKey(RedisConst.ACCOUNT_LOCK, sysUser.getAccount());
            Object count = redisUtil.get(key);
            if (!ObjectUtils.isEmpty(count)) {
                isNotLocked = (int) count < ymlConfigAuthLogin.getRetryCount();
            }
        }
        return new UserDetailEntity(sysUser, isNotLocked);
    }
}
